package com.cxlin.cwanandroid.ui.project

import android.os.Bundle
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter4.QuickAdapterHelper
import com.chad.library.adapter4.loadState.LoadState
import com.chad.library.adapter4.loadState.trailing.TrailingLoadStateAdapter
import com.cxlin.base.BaseFragment
import com.cxlin.base.ext.binding
import com.cxlin.base.ext.extraFragment
import com.cxlin.base.ext.startActivity
import com.cxlin.base.ext.toast
import com.cxlin.base.mvi.ext.collectFLow
import com.cxlin.cwanandroid.App
import com.cxlin.cwanandroid.R
import com.cxlin.cwanandroid.databinding.FragmentProjectBinding
import com.cxlin.cwanandroid.ui.browser.BrowserActivity
import com.cxlin.cwanandroid.ui.login.LoginActivity
import com.cxlin.cwanandroid.ui.login.viewmodel.LoginViewModel
import com.cxlin.cwanandroid.ui.project.adapter.ProjectAdapter
import com.cxlin.cwanandroid.ui.project.viewmodel.ProjectViewModel
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 *
 * @Author: chenxunlin
 * @Date: 2024/4/25 16:40
 */
class ProjectFragment : BaseFragment() {

    private val binding by binding<FragmentProjectBinding>()
    private val viewModel by viewModel<ProjectViewModel>()
    private val cid by extraFragment("cid", -1)
    private lateinit var helper: QuickAdapterHelper
    private val mAdapter by lazy {
        ProjectAdapter()
    }

    override fun getLayoutId() = R.layout.fragment_project


    override fun initView() {
        initRecyclerView()
    }

    private fun initRecyclerView() {
        mAdapter.run {
            addOnItemChildClickListener(
                R.id.articleStar
            ) { adapter, view, position ->
                if (App.CURRENT_USER == null) {
                    requireActivity().startActivity<LoginActivity>()
                } else {
                    mAdapter.getItem(position)?.run {
                        collect = !collect
                        viewModel.sendIntent(ProjectViewModel.ProjectUiIntent.CollectArticle(id, collect))
                    }
                    mAdapter.notifyItemChanged(position)
                }
            }
            addOnItemChildClickListener(R.id.root) { adapter, view, position ->
                requireActivity().startActivity<BrowserActivity>(
                    Bundle().apply {
                        putString("url", mAdapter.getItem(position)!!.link)
                    })
            }
        }
        helper = QuickAdapterHelper.Builder(mAdapter)
            .setTrailingLoadStateAdapter(object : TrailingLoadStateAdapter.OnTrailingListener {
                override fun onFailRetry() {
                    viewModel.sendIntent(ProjectViewModel.ProjectUiIntent.GetArticleList(cid, false))
                }

                override fun onLoad() {
                    viewModel.sendIntent(ProjectViewModel.ProjectUiIntent.GetArticleList(cid, false))
                }

            }).build()
        binding.recyclerView.apply {
            layoutManager = LinearLayoutManager(requireActivity())
            adapter = helper.adapter

        }
        binding.refreshLayout.apply {
            setOnRefreshListener {
                viewModel.sendIntent(ProjectViewModel.ProjectUiIntent.GetArticleList(cid, true))
            }
        }
    }

    override fun initData() {
        viewModel.sendIntent(ProjectViewModel.ProjectUiIntent.GetArticleList(cid, true))
    }

    override fun observeStateAndEvent() {
        viewModel.uiStateFlow.collectFLow(this) {
            when (this) {
                is ProjectViewModel.ProjectUiState.IsRefresh -> {
                    binding.refreshLayout.isRefreshing = this.result
                }

                is ProjectViewModel.ProjectUiState.Articles -> {
                    this.result?.let {
                        if (it.curPage == 1) {
                            mAdapter.submitList(it.datas)
                        } else {
                            mAdapter.addAll(it.datas)
                        }

                        // 如果在数据不满足一屏时，暂停加载更多，请调用下面方法
                        helper.trailingLoadStateAdapter?.checkDisableLoadMoreIfNotFullPage()
                        if (it.curPage >= it.pageCount) {/*
                            Set the status to not loaded, and there is no paging data.
                            设置状态为未加载，并且没有分页数据了
                             */
                            helper.trailingLoadState = LoadState.NotLoading(true)
                            Toast.makeText(requireActivity(), "没有更多数据了", Toast.LENGTH_SHORT)
                                .show()
                        } else {/*
                            Set the state to not loaded, and there is also paginated data
                            设置状态为未加载，并且还有分页数据
                             */
                            helper.trailingLoadState = LoadState.NotLoading(false)
                        }
                    }
                }
            }
        }

        viewModel.effectFlow.collectFLow(this){
            when(this){
                is LoginViewModel.LoginEvent.ToastEvent -> {
                    requireActivity().toast(
                        this.message,
                        if (this.short) Toast.LENGTH_SHORT else Toast.LENGTH_LONG
                    )
                }
            }
        }
    }
}